package io.github.mymonstercat.controller;

import io.github.mymonstercat.entity.Body;
import io.github.mymonstercat.entity.Result;
import io.github.mymonstercat.entity.VerificationVo;
import io.github.mymonstercat.service.TicketVisitsService;
import io.github.mymonstercat.service.impl.FileWarningServiceImpl;
import io.github.mymonstercat.utils.FileTransformer;
import io.github.mymonstercat.utils.FileUtils;
import io.github.mymonstercat.utils.Verification;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/v1")
public class FileWarningController {

    @Resource
    private TicketVisitsService ticketVisitsService;

    @Resource
    private FileTransformer fileTransformer;

    @Resource
    private FileWarningServiceImpl fileWarningService;

    @Value("${file.upload.window}")
    private String window;

    @Value("${file.upload.linux}")
    private String linux;

    @PostMapping("/uploadFile")
    public Result fileWarning(@RequestParam("file") MultipartFile file) throws IOException {
        // 开始计时
        long startTime = System.nanoTime();
        Result result = new Result();
        String name = Objects.requireNonNull(file.getOriginalFilename()).replaceAll(".*[\\\\/]", "");
        // 判断文件类型
        VerificationVo verificationVo = Verification.validateFile(file);
        if (0 == verificationVo.getStatus()) {
            result.setCode("500");
            result.setMessage(verificationVo.getMessage());
            result.setBody(new ArrayList<>());
            // 结束计时
            long endTime = System.nanoTime();
            // 计算并输出执行时间，单位为秒
            double executionTime = (endTime - startTime) / 1.0e9;
            ticketVisitsService.saveVisits("接口执行失败，原因为:" + verificationVo.getMessage() + "。执行时间为:" + executionTime + "秒", "log");
            return result;
        }
        String path = FileUtils.upload(file, window, linux);
        List<Body> list;
        if (1 == verificationVo.getStatus()) {
            list = new ArrayList<>();
            Body body = fileWarningService.getRate(path, name);
            if (body == null) {
                result.setCode("500");
                result.setMessage("系统异常");
                result.setBody(new ArrayList<>());
                // 结束计时
                long endTime = System.nanoTime();
                // 计算并输出执行时间，单位为秒
                double executionTime = (endTime - startTime) / 1.0e9;
                ticketVisitsService.saveVisits("接口执行失败，原因为:系统异常。执行时间为:" + executionTime + "秒", "log");
                return result;
            }
            body.setNum("1");
            list.add(body);
        } else {
            boolean existPageWithMoreThan30ChineseChars;
            existPageWithMoreThan30ChineseChars = fileTransformer.hasPageWithMoreThan30ChineseChars(path);
            if (existPageWithMoreThan30ChineseChars){
                list = fileTransformer.convertPagesWithMoreThan30ChineseCharsToImages(path, FileUtils.getPath(window, linux));
            }else {
                list = fileTransformer.PDFToImageDivision(name, path, FileUtils.getPath(window, linux));
            }
            if (list == null || list.size() <= 0) {
                result.setCode("500");
                result.setMessage("系统异常");
                result.setBody(new ArrayList<>());
                File f = new File(path);
                if (f.exists() && f.isFile()) {
                    if (f.delete()) {
                        log.info(path + "：文件删除成功");
                    } else {
                        log.info(path + "：文件删除失败");
                    }
                }
                // 结束计时
                long endTime = System.nanoTime();
                // 计算并输出执行时间，单位为秒
                double executionTime = (endTime - startTime) / 1.0e9;
                ticketVisitsService.saveVisits("接口执行失败，原因为:系统异常。执行时间为:" + executionTime + "秒", "log");
                return result;
            }
        }
        result.setCode("200");
        result.setMessage("");
        result.setBody(list);
        File f = new File(path);
        if (f.exists() && f.isFile()) {
            if (f.delete()) {
                log.info(path + "：文件删除成功");
            } else {
                log.info(path + "：文件删除失败");
            }
        }
        // 结束计时
        long endTime = System.nanoTime();
        // 计算并输出执行时间，单位为秒
        double executionTime = (endTime - startTime) / 1.0e9;
        ticketVisitsService.saveVisits("接口执行成功，返回值为:" + result + "。执行时间为:" + executionTime + "秒", "log");
        return result;
    }

    @PostMapping("/saveVisits")
    public void saveVisits() {
        String logMessage = "Log entry at " + LocalDateTime.now();
        ticketVisitsService.saveVisits(logMessage, "visits");
    }
}
